<?php
/**
 * 
 * @authors Liujinbi (857053791@QQ.com)
 * @date    2017-08-07 14:39:08
 * @version $Id$
 */
namespace app\mall\controller;
use think\Config;
use think\Db;
use think\Session;
use think\Controller;
use Wx\Wxpay\WxPaysdk;
use think\Log;
class Notify extends Controller {
    
    function __construct(){
        Log::init(Config::get('log_notify'));
        $config = Config::get('wx');
        $con = array_merge($config['pay'],$config['xcx']);
        $this->payApi = new WxpaySdk($con);
    }

    /**
     * 支付回掉接口
     * @return [type] [description]
     */
    function index(){
        // $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $xml = file_get_contents("php://input");
    	$needSign = false;
        Log::record('支付回调'.date('Y-m-d H:i:s'),'notify');
        Log::record($xml,'notify');
		$this->payApi->notify(array($this, 'NotifyCallBack'),$needSign);
    }

    /**
     * [NotifyCallBack description]
     * @param [type] $data 支付回掉数据
     * @param [type] &$msg 失败原因
     * @return [boolean] 处理成功放回true 处理失败放回false 并修改msg说明原因 
     */
    function NotifyCallBack($data, &$msg){
        // <xml><appid><![CDATA[wx3f66f045d56ce747]]></appid>
        // <bank_type><![CDATA[CFT]]></bank_type>
        // <cash_fee><![CDATA[1]]></cash_fee>
        // <fee_type><![CDATA[CNY]]></fee_type>
        // <is_subscribe><![CDATA[N]]></is_subscribe>
        // <mch_id><![CDATA[1487378482]]></mch_id>
        // <nonce_str><![CDATA[2o6fexq70ii4qd62sfvpdlh1n98hf13w]]></nonce_str>
        // <openid><![CDATA[oDJYA0b_HkVfzrby_gljXRhKvI6A]]></openid>
        // <out_trade_no><![CDATA[7100170821111284]]></out_trade_no>
        // <result_code><![CDATA[SUCCESS]]></result_code>
        // <return_code><![CDATA[SUCCESS]]></return_code>
        // <sign><![CDATA[5E7DE02BA14DC539110E9ECFE587C60E]]></sign>
        // <time_end><![CDATA[20170821111323]]></time_end>
        // <total_fee>1</total_fee>
        // <trade_type><![CDATA[JSAPI]]></trade_type>
        // <transaction_id><![CDATA[4009462001201708217405478165]]></transaction_id>
        // </xml>

    	// 为避免微信支付 商户订单号重复 问题，使用中间表sdzx_order_prepay
        $orderSn = $data['out_trade_no'];
    	//查出订单
    	$order = Db::field('*')->table('sdzx_order')->alias('o')
        ->join('sdzx_order_prepay p','o.order_id=p.order_id')
        ->where("p.out_trade_no='{$orderSn}'")->find();
    	if ($order) {
            if ($order['prepay_type'] == 1) {

                $change_order = Db::name('order_change')->where(['order_id'=>$order['order_id']])->order('change_id desc')->find();
                if ($change_order['pay_status']==1) {
                    return true;
                }else{
                    $updata = [
                        'pay_no'       => $data['transaction_id'],
                        'pay_time'     => date('Y-m-d H:i:s'),
                        'pay_money'    => $data['total_fee']/100, //转换为元
                        'pay_status'   => 1,
                        'pay_platform' => '微信支付'
                    ];

                    if ($order['order_status'] == 25) {
                        $re_change = Db::name('order')->where(['order_id'=>$order['order_id']])->update(['order_status'=>$change_order['bop_order_status']]);
                        if ($re_change===false) {
                            $msg='补价订单状态更新失败';
                            return false;
                        }
                    }

                    $re = Db::name('order_change')->where(['change_id'=>$change_order['change_id']])->update($updata);
                    if ($re!=false) {
                        Db::name('order_prepay')->where(['out_trade_no'=>$orderSn])->update(['status'=>1]);

                        Db::name('order_action')->insert([
                            'user_id'          => $order['user_id'],
                            'order_id'         => $order['order_id'],
                            'act_time'         => date('Y-m-d H:i:s'),
                            'order_status'     => $change_order['bop_order_status'],
                            'bop_order_status' => $order['order_status'],
                            'act_remark'       => '您已支付补价金额，请等待系统确认'
                        ]);

                        $this->sendTmp($order);
                        return true;
                    }else{
                        $msg='订单状态更新失败';
                        return false;
                    }
                }
            }else{
        		if ($order['pay_status'] == 1) { //已经处理
        			return true;
        		}else{
        			$updata = [
    					'pay_no'       => $data['transaction_id'],
    					'pay_time'     => date('Y-m-d H:i:s'),
    					'pay_money'    => $data['total_fee']/100, //转换为元
    					'pay_status'   => 1,
                        'pay_platform' => '微信支付'
        			];

                    if ($order['order_status'] == 0) {
                        $updata['order_status'] = 20;
                    }

                    $order['pay_time'] = $updata['pay_time'];
                    $order['pay_money'] = $updata['pay_money'];

        			$re = Db::name('order')->where(['order_id'=>$order['order_id']])->update($updata);
        			if ($re!=false) {
                        Db::name('order_prepay')->where(['out_trade_no'=>$orderSn])->update(['status'=>1]);

                        Db::name('order_action')->insert([
                            'user_id'          => $order['user_id'],
                            'order_id'         => $order['order_id'],
                            'act_time'         => date('Y-m-d H:i:s'),
                            'order_status'     => $updata['order_status'],
                            'bop_order_status' => $order['order_status']
                        ]);

                        // $this->sendTmp($order);
        				return true;
        			}else{
        				$msg='订单状态更新失败';
        				return false;
        			}
        		}
            }
    	}else{
    		$msg='订单不存在';
    		return false;
    	}
    }

    function sendTmp($order){
        // $prepay = Db::name('order_prepay')->where(['order_no'=>$order['order_no']])->find();
        // Db::name('order_prepay')->where(['order_no'=>$order['order_no']])->update(['status'=>1]);
        $d = [
            'touser'  => $order['openid'],
            'page'    => "pages/order_detail/order_detail?order_id={$order['order_id']}",
            'form_id' => $order['prepay_id'],
            'data' => [
                'keyword1'=>$order['order_no'], //单号
                'keyword2'=>date('Y-m-d H:i',strtotime($order['create_time'])), //下单时间
                'keyword3'=>"{$order['order_money']}", //订单金额
                'keyword4'=>'速冻在线商品', //商品名称
                'keyword5'=>"{$order['pay_money']}", //支付金额
                'keyword6'=>'微信支付', //支付方式
                'keyword7'=>date('Y-m-d H:i',strtotime($order['pay_time'])), //支付时间
            ],
            'emphasis_keyword' => 'keyword4.DATA'
        ];
        $re = sendPaytmp($d);
        if ($re !== true) {
            $d['error'] = $re;
            Log::record($d,'tmpmsg');
        }
    }
}